package Thread;

/****
 * 三个线程交替打印 0-100
 */
public class ThreadSwapPrintDemo {

    private  volatile Integer  number =0;
    private Object lock = new Object();

    public static void main(String[] args) {
        ThreadSwapPrintDemo ts = new   ThreadSwapPrintDemo();
        Thread thread1 = ts.getThread("thread1",100);
        Thread thread2 = ts.getThread("thread2",100);
        Thread thread3 = ts.getThread("thread3",100);
        thread1.start();
        thread2.start();
        thread3.start();


    }

    private Thread  getThread(String name,int max){
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while( number < max) {
                        print();
                }
            }
        });
        thread1.setName(name);
        return thread1;


    }
    public   void print(){
        synchronized (lock) {

            number++;
            System.out.println(Thread.currentThread().getName() + ":" + number);
            lock.notifyAll();
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}
